package de.mmis.core.base.abstracttree.serializer.selector;

import java.util.Map;

import de.mmis.core.base.Toolbox;
import de.mmis.core.base.gclass.GArray;
import de.mmis.core.base.gclass.GClass;
import de.mmis.core.base.gclass.GParameterized;

/**
 * {@link InstanceSelector} representing an already completely deserialized
 * object. The target type determines, if the deserialized object fits.
 * 
 * @author Christian Koch
 */
public class SimpleSelector extends InstanceSelector {

	private final Object object;

	public SimpleSelector(Object object, String id, Map<String, Object> idmap) {
		super(id, idmap);
		this.object = object;

		setID(this.object);
	}

	public static boolean checkType(Class<?> objClass, GClass gclass) {
		if (gclass instanceof GParameterized) {
			Class<?> baseclass = ((GParameterized) gclass).getBaseClass();
			return (baseclass.isAssignableFrom(objClass) || Toolbox
					.classEquals(baseclass, objClass));
		}
		if (gclass instanceof GArray) {
			if (!objClass.isArray())
				return false;

			return checkType(objClass.getComponentType(),
					((GArray) gclass).getComponentType());
		}
		return false;
	}

	@Override
	public Object createInstance(GClass gclass)
			throws InstanceSelectorException {
		if (this.object != null && !checkType(this.object.getClass(), gclass))
			throw new InstanceSelectorException("object \"" + this.object
					+ "\" of class " + this.object.getClass()
					+ " cannot be converted to type " + gclass);

		return this.object;
	}
}
